﻿using StarryEdge.Core;
using StarryEdge.Core.Models;
using StarryEdge.Core.Parameter;
using StarryEdge.Core.Tool;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace StarryEdge.Parameter
{
    public class UserEntity : InitFileBase, StarryEdge.Core.IInitFile, IUserEntity
    {
        private List<Core.Models.RoleModel> _roles;
        private List<Core.Models.UserModel> _users;
        private UserModel _loginUser;

        public UserEntity(IStarryEdgeLog runLog) : base(runLog, "init", "userdata")
        {
            Init();
        }

        public void Init()
        {
            if (File.Exists(_path))
            {
                string str = base.Read();
                if (!string.IsNullOrEmpty(str))
                {
                    Dictionary<string, object> keyValues = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(str);
                    _roles = System.Text.Json.JsonSerializer.Deserialize<List<Core.Models.RoleModel>>(keyValues["Role"].ToString());
                    string des = DESHelper.DESDecrypt(keyValues["UserData"].ToString(), _key, _iv);
                    _users = System.Text.Json.JsonSerializer.Deserialize<List<Core.Models.UserModel>>(des);
                }
            }
            if (_roles == null)
            {
                _roles = new List<Core.Models.RoleModel>();
            }
            if (_users == null)
            {
                _users = new List<Core.Models.UserModel>();
            }
        }

        private string _key = "12560695", _iv = "k164s453";

        public List<UserModel> Users => _users;

        public bool Save()
        {
            Dictionary<string, object> data = new Dictionary<string, object>();
            data.Add("Role", _roles);
            string des = DESHelper.DESEncrypt(System.Text.Json.JsonSerializer.Serialize(_users, OptionsHelper.Options), _key, _iv);
            data.Add("UserData", des);
            return Save(System.Text.Json.JsonSerializer.Serialize(data, OptionsHelper.Options));
        }

        void IUserEntity.Save()
        {
            Save();
        }

        public List<RoleModel> GetRoles() => _roles;

        public void AddRole(RoleModel role)
        {
            var model = _roles.FirstOrDefault(x => x.Id == role.Id);
            if (model == null)
            {
                _roles.Add(role);
            }
            else
            {
                model.Description = role.Description;
                model.Name = role.Name;
                model.UpdateTime = DateTime.Now;
                model.IsEnabled = role.IsEnabled;
                model.Level = role.Level;
            }
            Save();
        }

        public void RemoveRole(RoleModel role)
        {
            var model = _roles.FirstOrDefault(x => x.Id == role.Id);
            if (model != null)
            {
                _roles.Remove(model);
            }
        }

        public bool Login(string username, string password)
        {
            if (username == "admin" && password == "admin")
            {
                _loginUser = new UserModel() { Name = "调试账号", Role = new RoleModel() { Name = "管理员", IsEnabled = true, Level = 99 } };
                return true;
            }
            if (username == "admin" && password == "admin22345")
            {
                _loginUser = new UserModel() { Name = "开发人员", Role = new RoleModel() { Name = "超级管理员", IsEnabled = true, Level = 99 } };
                return true;
            }
            var model = _users.FirstOrDefault(x => x.Name == username && x.Password == password);
            if (model != null)
            {
                _loginUser = model;
                model.LoginTime = DateTime.Now;
            }
            else
            {
                _loginUser = default;
            }
            return model != null;
        }

        public bool LoginSwipeCard(string cardNumber)
        {
            var model = _users.FirstOrDefault(x => x.Password == cardNumber);
            if (model != null)
            {
                _loginUser = model;
            }
            else
            {
                _loginUser = default;
            }
            return model != null;
        }

        public void ExitLogin()
        {
            _loginUser = null;
        }

        public UserModel GetLoginUser()
        {
            return _loginUser;
        }

        public List<UserModel> GetUsers() => _users;

        public void AddUser(UserModel userModel)
        {
            var model = _users.FirstOrDefault(x => x.Id == userModel.Id);
            if (model == null)
            {
                _users.Add(userModel);
            }
            else
            {
                model.Address = userModel.Address;
                model.Name = userModel.Name;
                model.UpdateTime = DateTime.Now;
                model.Age = userModel.Age;
                model.Department = userModel.Department;
                model.FrameTime = userModel.FrameTime;
                model.IsFrameTime = userModel.IsFrameTime;
                model.Role = userModel.Role;
                model.LoginTime = userModel.LoginTime;
                model.PhoneNumber = userModel.PhoneNumber;
                model.Sex = userModel.Sex;
                model.Shift = userModel.Shift;
                model.Password = userModel.Password;
                model.Name = userModel.Name;
            }
            Save();
        }

        public void RemoveUser(UserModel userModel)
        {
            var model = _users.FirstOrDefault(x => x.Id == userModel.Id);
            if (model != null)
            {
                _users.Remove(model);
            }
        }

        private Action _outLoginAction;
        public void RestartOutLoginTime()
        {
            //退出登录事件
        }

        public void SetOutLoginAction(Action action)
        {
            if (_outLoginAction == null)
            {
                _outLoginAction = action;
            }
        }
    }
}
